package com.pifuke.patient;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.o.app.io.Extra;
import cn.o.app.util.OUtil;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.smiier.skin.QuestionDetailActivity;
import com.smiier.skin.adapter.QuestionAdapter;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.QuestionGetListTask.QuestionGetListRequest;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.smiier.skin.utils.Util;

public class SymptomQuestionActivity extends BasicActivity implements
		OnRefreshListener<ListView>, OnClickListener {

	public static class SymptomQuestionExtra extends Extra {
		public String symptom;
	}

	protected SymptomQuestionExtra mExtra;
	PullToRefreshListView mPullToRefresh;
	private RelativeLayout mAgeFilter;
	private RelativeLayout mSexFilter;
	private PopupWindow mPopSex, mPopAge;
	private int[] mLoc = new int[2];
	View mSexView;
	View mAgeView;
	long start_qid;
	int pageIndex;
	TextView mAgeTextView, mSexTextView;
	ArrayList<Object> array = new ArrayList<Object>();
	QuestionAdapter adapter;
	// private TextView text_empty;
	protected QuestionGetListRequest mRequest = new QuestionGetListRequest();
	HashMap<String, Object> params = new HashMap<String, Object>();
	private Drawable mArrowUp, mArrowDown;
	TextView mHeader;
	static final String mHeadString = "以下是有关“%s”的最新问题";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_symtom_question);
		init();
		Resources mRes = getResources();
		mHeader = new TextView(getContext());
		mHeader.setTextColor(getResources().getColor(R.color.text_gray));
		mHeader.setTextSize(12);
		mHeader.setPadding((int) OUtil.dp2px(getContext(), 12),
				(int) OUtil.dp2px(getContext(), 15), 0, 0);
		params.put(Constant.PARAM_API, "Question.GetList"
		// "Follow.GetList"
		);
		params.put("pageSize", Constant.pageSize);
		params.put("type", 2);
		if (GlobalSettings.sToken != null
				&& !GlobalSettings.sToken.trim().equals("")) {
			params.put("token", GlobalSettings.sToken);
		}
		mPopSex = Util.getPopWindow(getContext());
		mPopAge = Util.getPopWindow(getContext());
		mAgeTextView = (TextView) findViewById(R.id.age_arrow);
		mSexTextView = (TextView) findViewById(R.id.sex_arrow);
		mSexView = LayoutInflater.from(getContext()).inflate(
				R.layout.sex_filter, null);
		mAgeView = LayoutInflater.from(getContext()).inflate(
				R.layout.age_filter, null);
		mPopSex.setContentView(mSexView);
		mPopAge.setContentView(mAgeView);
		mArrowDown = mRes.getDrawable(R.drawable.arrow_down_white);
		mArrowUp = mRes.getDrawable(R.drawable.arrow_up_white);
		mArrowDown.setBounds(0, 0, mArrowDown.getIntrinsicWidth(),
				mArrowDown.getIntrinsicHeight());
		mArrowUp.setBounds(0, 0, mArrowUp.getIntrinsicWidth(),
				mArrowUp.getIntrinsicHeight());
		// text_empty = findViewById(R.id.text_empty, TextView.class);
		// mRequest.pageSize = GlobalSettings.PAGE_SIZE;
		// mRequest.token = GlobalSettings.sToken;
		mRequest.statuses = new ArrayList<Integer>();
		mRequest.statuses.add(3);
		mSexView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
		mAgeView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
		int width = CommonUtility.getScreenWidth(SymptomQuestionActivity.this);
		mPopSex.setWidth(width);
		mPopAge.setWidth(width);
		mAgeView.findViewById(R.id.age_1).setOnClickListener(this);
		mAgeView.findViewById(R.id.age_2).setOnClickListener(this);
		mAgeView.findViewById(R.id.age_3).setOnClickListener(this);
		mAgeView.findViewById(R.id.age_4).setOnClickListener(this);
		mAgeView.findViewById(R.id.age_5).setOnClickListener(this);
		mSexView.findViewById(R.id.sex_1).setOnClickListener(this);
		mSexView.findViewById(R.id.sex_2).setOnClickListener(this);
		mSexView.findViewById(R.id.sex_3).setOnClickListener(this);
		mPopAge.setHeight(mAgeView.getMeasuredHeight());
		mPopSex.setHeight(mSexView.getMeasuredHeight());
		mAgeFilter = (RelativeLayout) findViewById(R.id.age_filter);
		mSexFilter = (RelativeLayout) findViewById(R.id.sex_filter);
		mAgeFilter.setOnClickListener(this);
		mSexFilter.setOnClickListener(this);
		mPullToRefresh = findViewById(R.id.list_question,
				PullToRefreshListView.class);
		mPullToRefresh.setOnRefreshListener(this);

		mPullToRefresh.setPullLoadEnabled(false);
		mPullToRefresh.setScrollLoadEnabled(true);
		mPullToRefresh.getListView().addHeaderView(mHeader);
		mExtra = new SymptomQuestionExtra();
		// adapter = new QuestionAdapter();
		// adapter.setDataProvider(new ArrayList<QuestionAnswer>());
		if (mExtra.getFrom(getIntent())) {
			setNavTitle(mExtra.symptom);
			mRequest.Symptoms = new ArrayList<String>();
			mRequest.keyWord = mExtra.symptom;
			params.put("keyword", mExtra.symptom);
			mHeader.setText(String.format(mHeadString, mExtra.symptom));
		}
		mPullToRefresh.doPullRefreshing(true);
		mPullToRefresh.setAdapter(adapter);
		mPopAge.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				mAgeTextView.setCompoundDrawables(null, null, mArrowDown, null);
			}
		});
		mPopSex.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				mSexTextView.setCompoundDrawables(null, null, mArrowDown, null);
			}
		});
		mPullToRefresh.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int arg2, long arg3) {

				JSONObject object = (JSONObject) view.getTag(R.id.tag_obj);
				Intent intent = new Intent(activity,
						QuestionDetailActivity.class);
				intent.putExtra(Constant.IDENTITY_KEY, object.toString());
				startActivity(intent);

			}
		});
	}

	// ageRanges = 1,2,3 年龄段 逗号分隔 1 儿童：年龄0-12岁，2 青少年：年龄13-25岁，3 成年：26-50岁，4
	// 中老年：>50岁
	// sex = 1 性别 0 男 1女
	@Override
	public void onClick(View view) {
		if (mPopSex.isShowing()) {
			mPopSex.dismiss();
		}
		if (mPopAge.isShowing()) {
			mPopAge.dismiss();
		}
		mSexFilter.getLocationOnScreen(mLoc);
		int id = view.getId();
		switch (id) {
		case R.id.btn_left:
			finish();
			break;
		case R.id.age_filter:
			mAgeFilter.setBackgroundResource(R.drawable.rect_btn_blue);
			mSexFilter.setBackgroundColor(Color.TRANSPARENT);
			mAgeTextView.setCompoundDrawables(null, null, mArrowUp, null);

			mPopAge.showAtLocation(mSexFilter, Gravity.TOP, 0, mLoc[1]
					+ mSexFilter.getHeight());
			break;
		case R.id.sex_filter:
			mAgeFilter.setBackgroundColor(Color.TRANSPARENT);
			mSexFilter.setBackgroundResource(R.drawable.rect_btn_blue);
			mSexTextView.setCompoundDrawables(null, null, mArrowUp, null);

			mPopSex.showAtLocation(mSexFilter, Gravity.TOP, 0, mLoc[1]
					+ mSexFilter.getHeight());
			break;
		case R.id.age_1:
			start_qid = 0;
			params.put("ageRanges", "");
			array.clear();
			adapter.notifyDataSetChanged();
			loadData1();
			mAgeTextView.setText("年龄");
			break;
		case R.id.age_2:
			start_qid = 0;
			params.put("ageRanges", "1");
			array.clear();
			adapter.notifyDataSetChanged();
			loadData1();
			mAgeTextView.setText("年龄(儿童)");
			break;
		case R.id.age_3:
			start_qid = 0;
			params.put("ageRanges", "2");
			array.clear();
			adapter.notifyDataSetChanged();
			loadData1();
			mAgeTextView.setText("年龄(青少年)");
			break;
		case R.id.age_4:
			start_qid = 0;
			params.put("ageRanges", "3");
			array.clear();
			adapter.notifyDataSetChanged();
			loadData1();
			mAgeTextView.setText("年龄(成年)");
			break;
		case R.id.age_5:
			start_qid = 0;
			params.put("ageRanges", "4");
			array.clear();
			adapter.notifyDataSetChanged();
			loadData1();
			mAgeTextView.setText("年龄(中老年)");
			break;
		case R.id.sex_1:
			start_qid = 0;
			params.put("sex", "");
			array.clear();
			adapter.notifyDataSetChanged();
			loadData1();
			mSexTextView.setText("性别");

			break;
		case R.id.sex_2:
			start_qid = 0;
			params.put("sex", "0");
			array.clear();
			adapter.notifyDataSetChanged();
			loadData1();
			mSexTextView.setText("性别(男)");
			break;
		case R.id.sex_3:
			mSexTextView.setText("性别(女)");
			start_qid = 0;
			params.put("sex", "1");
			array.clear();
			adapter.notifyDataSetChanged();
			loadData1();
			break;
		default:
			break;
		}

	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		start_qid = 0;
		pageIndex = 0;
		array.clear();
		loadData1();
	}

	@Override
	protected void onResume() {
		super.onResume();
		start_qid = 0;
		pageIndex = 0;
		array.clear();
		loadData1();
	}

	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {
		loadData1();
	}

	private void loadData1() {
		params.put("startQid", start_qid);
		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						mPullToRefresh.onPullDownRefreshComplete();
						mPullToRefresh.onPullUpRefreshComplete();
						mPullToRefresh.setLastUpdateTime();
						if (!CommonUtility.isNull(o)) {
							JSONObject object = (JSONObject) o;
							if (CommonUtility.response200(object)) {
								try {

									object = object.getJSONObject("Res");
									JSONArray arr = (JSONArray) object
											.getJSONArray("Questions");
									if (arr.length() > 0) {
										CommonUtility.putAll(array, arr, true);
										mPullToRefresh.setHasMoreData(true);
									} else {
										if (array.size() > 0) {
											mPullToRefresh
													.setHasMoreData(false);
										} else {
											mPullToRefresh.getListView()
													.removeHeaderView(mHeader);
										}
									}
									if (array.size() > 0) {
										start_qid = ((JSONObject) array
												.get(array.size() - 1))
												.getInt("Qid");
										// text_empty.setVisibility(View.GONE);
									} else {
										// text_empty.setVisibility(View.VISIBLE);
									}
									if (CommonUtility.isNull(adapter)) {
										adapter = new QuestionAdapter(activity,
												array);
										mPullToRefresh.setAdapter(adapter);
									} else {
										adapter.notifyUpdate();
									}
									if (array.size() < 1) {
										/*
										 * if (mHeader.getParent() != null) {
										 * mPullToRefresh.getListView()
										 * .removeView(mHeader); }
										 */
										mPullToRefresh.setContextEmptyType(
												true, 2);
									} else {
										/*
										 * if (mHeader.getParent() == null) {
										 * mPullToRefresh.getListView()
										 * .addHeaderView(mHeader); }
										 */
										mPullToRefresh.setContextEmptyType(
												false, 2);
									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							} else {
								mPullToRefresh.setContextEmptyType(true, 2);
								CommonUtility.toast(activity,
										R.string.server_unavailable);
							}
						} else {
							mPullToRefresh.setContextEmptyType(true, 3);
						}
					}
				}), false, params);
	}

	/*
	 * @Override protected void onResume() { super.onResume();
	 * MobclickAgent.onResume(this); }
	 * 
	 * @Override protected void onPause() { super.onPause();
	 * 
	 * MobclickAgent.onPause(this); }
	 */
}